package cn.sc.summer.gateway.handler;

import cn.hutool.core.util.RandomUtil;
import cn.sc.summer.gateway.exception.CommonException;
import com.google.code.kaptcha.Producer;
import cn.sc.summer.constant.gateway.GatewayConstant;
import cn.sc.summer.redis.util.RedisHelper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 类名：图形验证码生成
 *
 * @author a-xin
 * @date 2023/8/18 10:48
 */
@Slf4j
@Configuration
@NoArgsConstructor
@AllArgsConstructor
public class CreateImageCodeHandler implements HandlerFunction<ServerResponse> {

    @Resource
    private Producer producer;

    @Value("${sms.captchaExpireTime:5}")
    private Integer SMS_EXPIRE_TIME;

    @Override
    @NonNull
    public Mono<ServerResponse> handle(@NonNull ServerRequest serverRequest) {

        //生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        //保存验证码信息
        String randomKey = RandomUtil.randomString(16);
        //设置有效期为2分钟
        RedisHelper.set(GatewayConstant.CODE_KEY + randomKey, text, 60L * SMS_EXPIRE_TIME, TimeUnit.SECONDS);
        log.warn("==> Start generating a graphical captcha: {}, Graphical captcha: {}", randomKey, text);
        // 转换流信息写出
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpeg", outputStream);
        } catch (IOException e) {
            throw new CommonException("ImageIO write err: " + e.getMessage(), e);
        }
        serverRequest.exchange().getResponse().getHeaders().set("imageRandomKey", randomKey);

        return ServerResponse
                .status(HttpStatus.OK)
                .contentType(MediaType.IMAGE_JPEG)
                .body(BodyInserters.fromResource(new ByteArrayResource(outputStream.toByteArray())));
    }
}

